package com.huya.controller.user;


import com.huya.common.constant.JwtClaimsConstant;
import com.huya.common.properties.JwtProperties;
import com.huya.common.result.Result;
import com.huya.common.utils.JwtUtil;
import com.huya.pojo.dto.UserLoginDTO;
import com.huya.pojo.dto.UserUpdateDTO;
import com.huya.pojo.entity.User;
import com.huya.pojo.vo.UserLoginVO;
import com.huya.pojo.vo.UserVO;
import com.huya.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Slf4j
public class UserController {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
//        log.info("login user: {}", userLoginDTO.getCode());
        //微信登录
        User user = userService.wxLogin(userLoginDTO);
        //为用户生成Jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

    /**
     * 查询用户信息
     * @param
     * @return
     */
    @GetMapping("/info")
    public Result<UserVO> getUserInfo(){
        //根据用户id查询用户信息
        UserVO userVO = userService.getUserInfo();
        return Result.success(userVO);
        }

    /**
     * 用户退出
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }


    /**
     * 更新用户信息
     * @param userUpdateDTO
     * @return
     */
    @PutMapping
    public Result update(@RequestBody UserUpdateDTO userUpdateDTO) {
        //根据用户id更新用户信息
        userService.update(userUpdateDTO);
        return Result.success();
    }
}
